//
//  LyMainTabBar.swift
//  SinaWeibo
//
//  Created by 蒋琪 on 2017/5/23.
//  Copyright © 2017年 liuying. All rights reserved.
//

import UIKit

class LyMainTabBar: UITabBar {

    var composeClousre:(() -> ())?
    
    //手写代码加载
    override init(frame:CGRect) {
        
        super.init(frame: frame)
        //添加撰写按钮
        addSubview(composeBtn)
        
        composeBtn.addTarget(self, action: #selector(composeBtnClick), for: .touchUpInside)
        
    }
    
    //当视图从xib或sb中加载的时候会执行这个方法,程序会崩溃
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //在swift中 默认给继承自NSObject的对象非私有方法/属性添加@objc
    //私有的方法/属性没有@objc标记
    //@objc对运行循环是可见的
    //撰写按钮被点击
    @objc private func composeBtnClick(){
    
        composeClousre?()
    
    }
    
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        let btnW = self.bounds.width / 5
        let btnH = self.bounds.height
        
        var index = 0
        //便利子视图
        for sV in subviews {
         
//            print(sV)
            //如果子控件是 UITabBarButton类型就修改button
            if sV.isKind(of: NSClassFromString("UITabBarButton")!) {
                sV.frame = CGRect(x: CGFloat(index) * btnW, y: 0, width: btnW, height: btnH)
                
//                if index == 2 {
//                    index += 1
//                }
//                index += 1

                index += (index == 1) ? 2 : 1
            }
        }
          //设置撰写按钮的frame
        composeBtn.bounds.size = CGSize(width: btnW, height: btnH)
        composeBtn.center = CGPoint(x: self.center.x, y: self.bounds.height * 0.5)
    }
    
    //通过懒加载实例化撰写微博的按钮
   private lazy var composeBtn : UIButton = {
    
        let  btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for:.highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        
        return btn
    }()
    
  
    
}
